﻿#ifndef TIMER_H
#define TIMER_H

#include <chrono>

#include <signalslot.h>
#include <eventloop.h>
#include <ReflectX_global.h>
#include <threadsafe.h>

//在当前的事件循环中创建一个定时器，该定时器的控制语句只能在当前线程中执行。
class REFLECTX_EXPORT Timer :public ThreadSafe::ThreadSafeBase{
private:
	struct TimerEvent;
	class TimerEventManager;
	struct TimerData;

public:
	typedef unsigned long TimerId;
	Timer();
	~Timer();

	void SetInterval(std::chrono::milliseconds interval);
	std::chrono::milliseconds GetInterval();

	void Start();
	void Start(std::chrono::milliseconds interval);
	void Stop();
	bool isActive() const;
	
public:
	Signal<> TimeOut;

public:
	static void SingleShot(std::chrono::milliseconds time,std::function<void()> fun,ThreadSafe::ThreadSafeBase* context);
	static void SingleShot(std::chrono::system_clock::time_point timepoint, std::function<void()> fun, ThreadSafe::ThreadSafeBase* context);

protected:
	virtual void HandleTimerEvent(ThreadSafe::TimerEvent* event);
	void HandleEvent(ThreadSafe::Event* event) override;

private:
	void PostEvent(std::chrono::system_clock::time_point startTime);
private:
	bool m_bisActive;
	std::chrono::milliseconds interval;
	TimerId id;
	EventLoop::ThreadId currentThread;
	bool isPosted;
	friend class TimerEventManager;
};


#endif // !TIMER_H
